<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
// import echarts from 'echarts'
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import chartNoData from './img/chartNoData.png'
import elementResizeDetectorMaker from 'element-resize-detector'
// import { debounce } from '@/utils/decorator.js'
export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    loadingText: {
      type: String,
      default: '数据正在努力加载...'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  mounted() {
    this.chart = echarts.init(this.$el, 'macarons')
    this.showLoading()

    const _this = this
    elementResizeDetectorMaker().listenTo(document.getElementsByClassName(this.className), element => {
      _this.$nextTick(() => {
        _this.changeReSize()
      })
    })
  },
  methods: {
    /**
     * 初始化
     * @param {Object} option
     */
    initChart(option) {
      this.chart.clear()
      this.chart = echarts.init(this.$el, 'macarons')
      this.hideLoading()
      this.chart.setOption(option)
    },
    /**
     * 显示loading
     */
    showLoading() {
      this.chart.showLoading({
        text: this.loadingText,
        color: '#409eff',
        lineWidth: 2
      })
    },
    /**
     * 隐藏loading
     */
    hideLoading() {
      this.chart.hideLoading()
    },
    /**
     * 显示空布局
     */
    showEmpty() {
      this.initChart({
        title: {
          text: ['{a|}', '{b|暂无数据}'].join('\n'),
          x: 'center',
          y: 'center',
          textStyle: {
            rich: {
              a: {
                backgroundColor: {
                  image: chartNoData
                },
                height: 40
              },
              b: {
                color: '#C2C7CF'
              }
            }
          }
        }
      })
    },
    // @debounce(100) // 防抖
    changeReSize() {
      // 监听到事件后执行的业务逻辑
      this.resize()
    }
  }
}
</script>
